package jblip.gui.components.view;

import java.awt.Dimension;
import java.awt.Image;

import javax.swing.Box;
import javax.swing.BoxLayout;

import jblip.gui.IconLoader;
import jblip.gui.JBlip;
import jblip.gui.components.ImageChangePanel;
import jblip.gui.data.images.IconCache;
import jblip.resources.Update;
import jblip.resources.UpdateType;
import jblip.resources.UserPicture.PictureSize;

public class UpdateComponent extends ChannelViewComponent<Update> {
  private static final long serialVersionUID = 1L;

  private static final Image AV_DEFAULT;

  private static final Image ARROW_PM;

  private static final Image ARROW_DM;

  private static final Integer FIXED_WIDTH = 500;

  private static final Dimension MIN_SIZE = new Dimension(FIXED_WIDTH, 10);

  private static final Dimension MAX_SIZE =
      new Dimension(FIXED_WIDTH, Integer.MAX_VALUE);

  static {
    AV_DEFAULT = IconLoader.loadIcon("nano_anon.png").getImage();
    ARROW_PM = IconLoader.loadIcon("arrow_pm.png").getImage();
    ARROW_DM = IconLoader.loadIcon("arrow_dm.png").getImage();
  }

  UpdateComponent(final Update update) {
    super(update);

    final BoxLayout layout = new BoxLayout(this, BoxLayout.X_AXIS);
    this.setLayout(layout);

    final IconCache icons = JBlip.instance().getIconCache();

    final ImageChangePanel sender_av = new ImageChangePanel(AV_DEFAULT);
    String src_user = null;
    if (data.getSrcUser() == null) {
      src_user = data.getSrcUserLogin();
    } else {
      src_user = data.getSrcUser().getLogin();
    }
    icons.getUserIcon(src_user, PictureSize.NANO, sender_av);
    sender_av.setToolTipText("^" + src_user);
    this.add(sender_av);

    if (update.getType().hasRecipient()) {
      if (update.getType().equals(UpdateType.DIRMSG)) {
        this.add(new ImageChangePanel(ARROW_DM));
      } else if (update.getType().equals(UpdateType.PRIVMSG)) {
        this.add(new ImageChangePanel(ARROW_PM));
      }
      final ImageChangePanel receiver_av = new ImageChangePanel(AV_DEFAULT);
      String dst_user = null;

      if (data.getDstUser() == null) {
        dst_user = data.getDstUserLogin();
      } else {
        dst_user = data.getDstUser().getLogin();
      }
      icons.getUserIcon(dst_user, PictureSize.NANO, receiver_av);
      receiver_av.setToolTipText("^" + dst_user);
      this.add(receiver_av);
    }

    final TextViewPane body = new TextViewPane(data.getBody());
    body.setBackground(ComponentBorder.COLOR);

    this.add(Box.createHorizontalStrut(5));
    this.setOpaque(false);
    this.add(body);
  }

  @Override
  public Dimension getMaximumSize() {
    return MAX_SIZE;
  }

  @Override
  public Dimension getMinimumSize() {
    return MIN_SIZE;
  }

  @Override
  public Dimension getPreferredSize() {
    final Dimension pref = super.getPreferredSize();
    if (pref.height < 10) {
      return MIN_SIZE;
    } else {
      return new Dimension(FIXED_WIDTH, pref.height);
    }
  }
}
